package com.lzxuni.modules.qualityAssurance;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzxuni.common.annotation.SysLog;
import com.lzxuni.common.utils.R;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.common.utils.UuidUtil;
import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.common.entity.FileEntity;
import com.lzxuni.modules.common.service.FileEntityService;
import com.lzxuni.modules.dataAcquisition.entity.Chain;
import com.lzxuni.modules.dataAcquisition.entity.ChainLinkProcess;
import com.lzxuni.modules.dataAcquisition.entity.ProductIndex;
import com.lzxuni.modules.dataAcquisition.service.ChainLinkProcessService;
import com.lzxuni.modules.dataAcquisition.service.ChainLinkService;
import com.lzxuni.modules.dataAcquisition.service.ChainService;
import com.lzxuni.modules.dataAcquisition.service.ProductIndexService;
import com.lzxuni.modules.enterprise.entity.EnterpriseInfo;
import com.lzxuni.modules.enterprise.service.EnterpriseInfoService;
import com.lzxuni.modules.productdisplay.entity.ProductDisplay;
import com.lzxuni.modules.productdisplay.service.ProductDisplayService;
import com.lzxuni.modules.qualityAssurance.entity.ProductSampling;
import com.lzxuni.modules.qualityAssurance.entity.ProductSamplingIndex;
import com.lzxuni.modules.qualityAssurance.service.ProductSamplingIndexService;
import com.lzxuni.modules.qualityAssurance.service.ProductSamplingService;
import com.lzxuni.modules.system.entity.BaseArea;
import com.lzxuni.modules.system.service.BaseAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 产品抽检 前端控制器
 * </p>
 *
 * @author wzx
 * @since 2019-07-15
 */
@RestController
@RequestMapping("/LR_QualityAssurance/ProductSampling")
public class ProductSamplingController extends BaseController {

    @Autowired
    private ProductSamplingService samplingService;
    @Autowired
    private ProductSamplingIndexService samplingIndexService;
    @Autowired
    private ProductDisplayService productService;
    @Autowired
    private EnterpriseInfoService enterpriseInfoService;
    @Autowired
    private BaseAreaService areaService;
    @Autowired
    private ChainService chainService;
    @Autowired
    private ChainLinkService linkService;
    @Autowired
    private ChainLinkProcessService processService;
    @Autowired
    private ProductIndexService productIndexService;
    @Autowired
    private FileEntityService fileEntityService;

    @RequestMapping("/Index")
    @SysLog(categoryId = 2, module = "产品抽检", operateType = "访问")
    public ModelAndView list() {
        ModelAndView mv = new ModelAndView("/LR_QualityAssurance/ProductSampling/index");
        return mv;
    }

    @RequestMapping("/Query")
    public Object query(String code) throws Exception{
        if (StringUtils.isNotEmpty(code)) {
            ProductDisplay product = productService.getOne(new QueryWrapper<ProductDisplay>().eq("traceability_code",code));
            if (product != null) {
                Map<String, Object> map = new HashMap<>();
                Chain chain = chainService.getById(product.getTraceabilityChain());
                product.setChainName(chain == null ? "" : chain.getChainName());
                map.put("product", product);
                EnterpriseInfo enterpriseInfo = enterpriseInfoService.getById(product.getAffiliatedEnterprises());
                String addresss = "";
                BaseArea area1 = areaService.getById(enterpriseInfo.getProvinceId());
                BaseArea area2 = areaService.getById(enterpriseInfo.getCityId());
                BaseArea area3 = areaService.getById(enterpriseInfo.getCountyId());
                BaseArea area4 = areaService.getById(enterpriseInfo.getTownId());
                BaseArea area5 = areaService.getById(enterpriseInfo.getVillageId());
                addresss = area1 == null ? addresss : addresss + area1.getAreaName() + " ";
                addresss = area2 == null ? addresss : addresss + area2.getAreaName() + " ";
                addresss = area3 == null ? addresss : addresss + area3.getAreaName() + " ";
                addresss = area4 == null ? addresss : addresss + area4.getAreaName() + " ";
                addresss = area5 == null ? addresss : addresss + area5.getAreaName() + " ";
                enterpriseInfo.setAddress(addresss);
                map.put("enterprise", enterpriseInfo);
                List<ChainLinkProcess> processes = new ArrayList<>();
                List<ProductIndex> productIndices = productIndexService.list(new QueryWrapper<ProductIndex>().eq("product_id", product.getYwId()).groupBy("process_id"));
                if (productIndices != null && productIndices.size() > 0) {
                    for (ProductIndex productIndex : productIndices) {
                        ChainLinkProcess process = processService.getById(productIndex.getProcessId());
                        if (process != null) {
                            List<ProductIndex> productIndexList = productIndexService.list(new QueryWrapper<ProductIndex>().eq("product_id", product.getYwId()).eq("process_id", process.getId()));
                            if (productIndexList != null && productIndexList.size() > 0) {
                                for (ProductIndex index : productIndexList) {
                                    if(index.getCollectionType().equals("图片") || index.getCollectionType().equals("视频")){
                                        FileEntity fileEntity = new FileEntity();
                                        fileEntity.setYwId(index.getProductIndexId());
                                        fileEntity.setYwType(index.getCollectionType().equals("图片") ? "indexPic" : "indexFile");
                                        index.setFileEntityList(fileEntityService.queryListByFileEntity(fileEntity));
                                    }
                                }
                            }
                            process.setProductIndexList(productIndexList);
                            processes.add(process);
                        }
                    }
                }
                map.put("processes", processes);
                return R.ok().put("data", map);
            }else{
                return R.error("该溯源码未查找到产品！");
            }
        }
        return R.error("溯源码不能为空！");
    }

    @RequestMapping("/Form")
    public ModelAndView insert(String productId, String data) throws Exception {
        ModelAndView mv = new ModelAndView("/LR_QualityAssurance/ProductSampling/form");
        ProductDisplay product = productService.getById(productId);
        EnterpriseInfo enterpriseInfo = enterpriseInfoService.getById(product == null ? "" : product.getAffiliatedEnterprises());
        product.setEnterpriseName(enterpriseInfo == null ? "" : enterpriseInfo.getEnterpriseName());
        mv.addObject("data", data);
        mv.addObject("product", product);
        return mv;
    }

    @RequestMapping("/SaveForm")
    @SysLog(categoryId = 3, module = "产品抽检", operateType = "举证")
    public Object insertDo(HttpServletRequest request, ProductSampling sampling, String data, String proofFiles) throws Exception {
        String uid = UuidUtil.get32UUID();
        sampling.setSamplingId(uid);
        sampling.setUserId(getUserId());
        sampling.setCreateTime(new Date());
        samplingService.save(sampling);
        if (StringUtils.isNotEmpty(proofFiles)) {
            fileEntityService.insert(proofFiles.replace("&quot;", "\""), uid, "ntp", "proofFiles", null);
        }
        String[] arrs = data.split(",");
        for (int i = 0; i < arrs.length; i++) {
            ProductSamplingIndex samplingIndex = new ProductSamplingIndex();
            samplingIndex.setSamplingId(uid);
            samplingIndex.setProductIndexId(arrs[i]);
            samplingIndexService.save(samplingIndex);
        }
        return R.ok("举证成功！");
    }

}

